package cn.jasonone.jasonfx.entity;

import java.net.URL;

import cn.jasonone.jasonfx.annotation.FXController;
import cn.jasonone.jasonfx.exception.ControllerException;
import cn.jasonone.jasonfx.factory.ModeFactory;
import cn.jasonone.jasonfx.util.ControllerUtil;
import cn.jasonone.jasonfx.util.Resources;
import cn.jasonone.jasonfx.util.StringUtil;
import cn.jasonone.jasonfx.util.WindowUtil;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.Setter;

/**
 * @Author Jason
 * @Date 2020/1/18 21:25
 * @Version 1.0
 */
public class JFXBaseController extends Pane {
	private static final String FXML_SUFFIX = ".fxml";
	@Setter
	@Getter
	private Stage stage;
	@Getter
	private URL path;

	public JFXBaseController() {
	}

	public void init() {
		Class<? extends JFXBaseController> type = getClass();
		if (!ControllerUtil.isController(this)) {
			throw new ControllerException("非法的控制器,请检查是否缺少FXController注解");
		}
		// 解析FXML的URL对象
		FXController controller = type.getAnnotation(FXController.class);
		this.path = type.getResource(type.getSimpleName() + FXML_SUFFIX);
		if (StringUtil.isNotEmpty(controller.path())) {
			this.path = Resources.getFile(controller.path());
		}
	}

	/**
	 * 显示窗口
	 * 
	 * @param wait 是否挂起父窗口
	 */
	public void show(boolean wait) {
		if (WindowUtil.isWindow(this)) {
			if (wait) {
				this.stage.showAndWait();
			} else {
				this.stage.show();
			}
		}
	}

	/**
	 * 显示窗口
	 */
	public void show() {
		show(false);
	}

	/**
	 * 关闭窗口
	 */
	public void close() {
		if (WindowUtil.isWindow(this)) {
			this.stage.close();
		}
	}
}
